package com.github.icloudpay.pay.core.service.pay;

import java.nio.charset.Charset;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.icloudpay.pay.core.inter.SignatureService;
import com.github.icloudpay.pay.core.service.pay.alipay.util.AliPayConfig;
import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.common.util.RSA;



/**
 * 本地签名服务
 * 
 * @author zhangjun
 * 
 *         2015-7-29
 */
@Service("localSignatureService")
public class LocalSignatureService implements SignatureService {

	private static final Logger logger = (Logger) LoggerFactory.getLogger(LocalSignatureService.class);

	@Autowired
	private AliPayConfig aliPayConfig;

	@Override
	public String sign(String toBeSign, Map<String, Object> configMap) {
		logger.info("调用本地签名服务开始,待签名字符串:{},支付通道:{}", toBeSign, configMap.get("payCompanyNo"));

		String sign = getSign(toBeSign, configMap);

		logger.info("调用本地签名服务完成,签名串:{}", sign);

		return sign;
	}

	private String getSign(String toBeSign, Map<String, Object> configMap) {
		if ("ALIPAY".equals((String)configMap.get("payCompanyNo"))) { // 支付宝
			if ("RSA".equalsIgnoreCase((String)configMap.get("encryptionMethod"))) {
				logger.info("支付宝RSA签名");
				return RSA.sign(toBeSign, (String)configMap.get("outMerPrivateKey"), "UTF-8");
			} else {
				logger.info("支付宝MD5签名");
				return MD5.sign(toBeSign, (String)configMap.get("outMerPrivateKey"), "UTF-8");
			}
			
		} else if ("WECHAT".equals((String)configMap.get("payCompanyNo"))) { // 腾讯
			logger.info("微信MD5签名");
			String result = toBeSign + "&key=" + (String)configMap.get("outMerPrivateKey");
			return DigestUtils.md5Hex(result.getBytes(Charset.forName("UTF-8"))).toUpperCase();
			
		}
		return null;
	}

	@Override
	public boolean verify(String toBeSign, String sign, Map<String, Object> configMap) {
		// 支付宝
		if ("ALIPAY".equals((String)configMap.get("payCompanyNo"))) {
			if ("RSA".equalsIgnoreCase((String)configMap.get("encryptionMethod"))) {
				return RSA.verify(toBeSign, sign, aliPayConfig.getAli_public_key(), "UTF-8");
			} else {
				return MD5.verify(toBeSign, sign, (String)configMap.get("encryptionMethod"), "UTF-8");
			}
		} else if ("WECHAT".equals((String)configMap.get("payCompanyNo"))) {
			String result = toBeSign + "&key=" + (String)configMap.get("encryptionMethod");
			String mysign = DigestUtils.md5Hex(result.getBytes(Charset.forName("UTF-8"))).toUpperCase();
			if (sign.equalsIgnoreCase(mysign)) {
				return true;
			}
			return false;
		}

		return false;
	}

}
